package mango.orm.impl;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

import mango.functions.FuncDate;
import mango.functions.FuncString;
import mango.orm.Dao;
import mango.orm.DaoIterator;
import mango.orm.OrmException;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;



public class StringIterator extends DaoIterator<String> {

    public StringIterator(Dao dao, DBSession session, boolean selfClose, ResultSet rs, Class<String> retType)
            throws SQLException {
        super(dao, session, selfClose, rs, retType);
    }

    public String next() {
        try {
            if (!this.hasNext) {
                throw new OrmException("not support next()");
            }
            String result = null;
            ResultSetMetaData meta = this.rs.getMetaData();
            int type = meta.getColumnType(1);
            if (type == Types.DATE) {
                java.util.Date date = new java.util.Date(rs.getDate(1).getTime());
                result = FuncDate.parse(date);
            }
            else if (type == Types.TIMESTAMP) {
                java.sql.Timestamp time = rs.getTimestamp(1);
                java.util.Date date = new java.util.Date(time.getTime());
                result = FuncDate.parseDateTime(date);
            }
            else if (type == Types.TIME) {
                java.sql.Time time = rs.getTime(1);
                java.util.Date date = new java.util.Date(time.getTime());
                result = FuncDate.parse("hh:mm:ss", date);
            }
            else if (type == Types.BLOB) {
                result = "";
            }
            else {
                result = FuncString.encodeString(rs.getString(1));
            }
            this.postNext();
            return result;
        }
        catch (Exception e) {
            if (this.selfClose) {
                DBSessionFactory.closeSession(session);
            }
            throw new OrmException(e);
        }
    }
}
